/**
 * 
 */
package com.idea.auction.controller;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import com.idea.auction.model.Permission;
import com.idea.auction.model.Role;
import com.idea.auction.service.PermissionService;
import com.idea.auction.service.RolePerService;
import com.idea.auction.service.RoleService;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.StrKit;
import com.jfinal.server.Service;

/**
 * @author y.z
 */
@ControllerBind(controllerKey="/role",viewPath="/pages")
public class RoleController extends BaseController {
	private static final Logger log = Logger.getLogger(RoleController.class);
	@Service
	private RoleService roleService;
	@Service
	private PermissionService permissionService;
	@Service
	private RolePerService rolePerService;
	
	/**
	 * 跳转到角色页
	 */
	@RequiresPermissions("role/toRole")
	public void toRole(){
		getNavigation();
		render("role/role-list.html");
	}
	
	/**
	 * 角色编辑页面
	 */
	public void toEditRole(){
		Role role = new Role();
		
		if(!StrKit.isBlank(this.getPara("id"))){
			role = roleService.getById(this.getParaToInt("id"));
		}
		setAttr("role", role);
		render("role/role-edit.html");
	}
	
	/**
	 * 跳转到权限编辑页面
	 */
	public void toEditRolePer(){
		List<Permission> permissionList = permissionService.getPermissionList(this.getPara("id"));
		setAttr("roleId", this.getPara("id"));
		setAttr("permissionList", permissionList);
		render("role/role-per-edit.html");
	}
	
	/**
	 * 获取角色分页
	 */
	public void getRoleList(){
		if(!StrKit.isBlank(getPara("curPage"))){
			curPage = getParaToInt("curPage");
		}
		super.setPage(roleService.getPage(curPage));
	}
	
	/**
	 * 添加角色
	 */
	public void addRole(){
		Role role = new Role();
		role.set("role_name",this.getPara("roleName") );
		role.set("description", this.getPara("roleDesc"));
		role.set("create_date", new Date());
		
		if(roleService.add(role)){
			msgAdd();
		}
		
	}
	
	/**
	 * 编辑角色
	 */
	public void editRole(){
		Role role = new Role();
		role.set("id",this.getPara("roleId") );
		role.set("role_name",this.getPara("roleName") );
		role.set("description", this.getPara("roleDesc"));
		role.set("create_date", new Date());
		
		if(roleService.update(role)){
			msgUpdate();
		}
		
	}
	
	/**
	 * 删除角色
	 */
	public void delRole(){
		String ids = getPara("ids");
		String idArray[] = ids.split(",");
		
		for(String id:idArray){
			roleService.del(Integer.parseInt(id));
		}
		
		msgSuccess();
	}
	
	/**
	 * 编辑权限
	 */
	public void editRolePer(){
		
		if(rolePerService.addRolePer(this.getPara("roleId"), this.getPara("perIds"))){
			msgUpdate();
		}
	}
	
}	